const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📬 获取用户通知')
  
  try {
    const { OPENID } = cloud.getWXContext()
    const { page = 1, pageSize = 10, markAsRead = false } = event
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 计算跳过的记录数
    const skip = (page - 1) * pageSize
    
    // 获取用户通知总数
    const countResult = await db.collection('user_notifications')
      .where({
        targetOpenid: OPENID
      })
      .count()
    
    const totalCount = countResult.total
    
    // 获取用户通知列表
    const notificationsResult = await db.collection('user_notifications')
      .where({
        targetOpenid: OPENID
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 处理通知数据
    const notifications = notificationsResult.data.map(notification => ({
      _id: notification._id,
      type: notification.type,
      title: notification.title,
      content: notification.content,
      data: notification.data || {},
      isRead: notification.isRead || false,
      createTime: notification.createTime,
      readTime: notification.readTime
    }))
    
    // 如果需要标记为已读
    if (markAsRead && notifications.length > 0) {
      const unreadIds = notifications
        .filter(n => !n.isRead)
        .map(n => n._id)
      
      if (unreadIds.length > 0) {
        // 批量标记为已读
        const batch = db.batch()
        unreadIds.forEach(id => {
          batch.update(db.collection('user_notifications').doc(id), {
            data: {
              isRead: true,
              readTime: new Date()
            }
          })
        })
        
        await batch.commit()
        console.log(`✅ 标记 ${unreadIds.length} 条通知为已读`)
      }
    }
    
    // 获取未读通知数量
    const unreadCountResult = await db.collection('user_notifications')
      .where({
        targetOpenid: OPENID,
        isRead: db.command.neq(true)
      })
      .count()
    
    console.log(`✅ 获取到 ${notifications.length} 条通知，未读 ${unreadCountResult.total} 条`)
    
    return {
      success: true,
      data: {
        notifications: notifications,
        pagination: {
          page: page,
          pageSize: pageSize,
          totalCount: totalCount,
          totalPages: Math.ceil(totalCount / pageSize),
          hasMore: skip + notifications.length < totalCount
        },
        unreadCount: unreadCountResult.total
      }
    }
    
  } catch (error) {
    console.error('❌ 获取用户通知失败:', error)
    return {
      success: false,
      error: error.message || '获取通知失败'
    }
  }
}
